package cn.itcast.demo;

import cn.itcast.domain.Items;
import cn.itcast.domain.Orders;
import cn.itcast.domain.User;
import cn.itcast.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class Demo {
    private UserMapper mapper = null;
    private SqlSession sqlSession = null;

    @Before
    public void before() throws Exception {
        //1.加载核心配置文件,并构建sqlsessionfactory工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlConfig.xml"));
        //2.获取sqlsession对象
        sqlSession = sqlSessionFactory.openSession();
        //3.获取接口代理对象
        mapper = sqlSession.getMapper(UserMapper.class);

    }

    @After
    public void after() {
        //5.提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

    @Test
    public void findUserAndNumberAndName() {

        List<User> userList = mapper.findUser();
        for (User user : userList) {
            System.out.println("用户名称 : " + user.getUsername());
            List<Orders> ordersList = user.getOrdersList();
            for (Orders orders : ordersList) {
                System.out.println("订单编号 : "+ orders.getNumber());
                List<Items> itemsList = orders.getItemsList();
                for (Items items : itemsList) {
                    System.out.println("商品名称 : " + items.getName());
                }
            }
        }

    }
}
